package com.ai.emall.business.impl;

import java.util.List;

import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ai.emall.bean.gbean.MallProductModule;
import com.ai.emall.bean.gbean.MallProductModuleExample;
import com.ai.emall.bean.gbean.MallProductModuleExample.Criteria;
import com.ai.emall.bean.gbean.Product;
import com.ai.emall.bean.gbean.ProductPicture;
import com.ai.emall.bean.gbean.ProductSku;
import com.ai.emall.business.interfaces.IProductManageDealSV;
import com.ai.emall.constants.EmallBusiConstants;
import com.ai.emall.dao.gdao.MallProductModuleMapper;
import com.ai.emall.dao.gdao.ProductMapper;
import com.ai.emall.dao.gdao.ProductPictureMapper;
import com.ai.emall.dao.gdao.ProductSkuMapper;
import com.ai.emall.service.interfaces.IMallProductModuleSV;
import com.ai.emall.service.interfaces.IProductSkuSV;
import com.ai.emall.utils.constants.SysExceptCodeConstants;
import com.ai.emall.utils.exception.BusinessException;
import com.ai.emall.utils.util.CollectionUtil;
import com.ai.emall.utils.util.DateUtil;
import com.ai.gcf.api.emall.productmanage.param.ModifyProductInfoRequest;
import com.ai.gcf.api.emall.productmanage.param.SaveProductInfoRequest;


/** 
 * 
 * @author zhaowg3
 * @Date 2016年12月30日
 */
@Service
public class ProductManageDealSVImpl implements IProductManageDealSV{
	@Autowired
	private ProductMapper productMapper;
	@Autowired
	private ProductPictureMapper pictureMapper;
	@Autowired
	private MallProductModuleMapper moduleMapper;
	@Autowired
	private ProductSkuMapper productSkuMapper;
	@Autowired
	private IMallProductModuleSV iMallProductModuleSV;
	@Autowired
	private IProductSkuSV iProductSkuSV;
	private Log logger = LogFactory.getLog(ProductManageDealSVImpl.class);
	@Override
	public Long saveProductInfo(SaveProductInfoRequest request) throws Exception {
		logger.info("保存商品信息");
		Product product = new Product();
		product.setName(request.getProductName());
		product.setProductDesc(request.getProductDesc());
		product.setCreaterId((Long)ObjectUtils.defaultIfNull(request.getOperId(), 0L));
		product.setCreateTime(DateUtil.getSysDate());
		product.setParam(request.getGmProductId()+EmallBusiConstants.Product.PARAM_SPLIT+request.getGmSkuid());
		product.setDrainageUrl(request.getProductLink());
		product.setSort(1L);
		productMapper.insertSelective(product);
		
		logger.info("保存商品图片");
		ProductPicture productPicture = new ProductPicture();
		productPicture.setVfsId(request.getProductPictureDir());
		productPicture.setStatus(EmallBusiConstants.ProductPicture.Status.VALID);
		pictureMapper.insertSelective(productPicture);
		
		logger.info("保存商品模块信息");
		MallProductModule productModule = new MallProductModule();
		productModule.setProductId(product.getProductId());
		productModule.setModuleId(request.getModuleId());
		productModule.setStatus(EmallBusiConstants.MallProductModule.Status.DOWN);
		productModule.setPictId(productPicture.getPicId());
		productModule.setCreaterId(((Long)ObjectUtils.defaultIfNull(request.getOperId(), 0L)));
		productModule.setCreateTime(DateUtil.getSysDate());
		//获取该商品在模块中的排序位置
		long moduleSort = iMallProductModuleSV.getMaxSortByModuleId(request.getModuleId(), EmallBusiConstants.MallProductModule.Status.DOWN);
		productModule.setModuleSort(moduleSort+1);
		moduleMapper.insert(productModule);
		
		//活动区和广告区不需要保存sku表
		if(!request.getModuleId().equals(EmallBusiConstants.MallProductModule.ModuleId.AREA_ACTIVITY) 
				&& !request.getModuleId().equals(EmallBusiConstants.MallProductModule.ModuleId.AREA_ADVERTISEMENT)){
			logger.info("保存商品SKU表");
			ProductSku productSku = new ProductSku();
			productSku.setProductId(product.getProductId());
			productSku.setPriceMode(request.getPriceType());
			productSku.setNormalPrice(parseDouble(request.getNormalPrice()));
			productSku.setDiscount(parseDouble(request.getDisCount()));
			productSku.setSailPrice(parseDouble(request.getSailPrice()));
			productSku.setSailPriceTs(DateUtil.getCurrentTimeMillis());
			productSku.setStatus(EmallBusiConstants.ProductSku.Status.DOWN);
			productSku.setCreaterId(request.getOperId());
			productSku.setCreateTime(DateUtil.getSysDate());
			productSku.setCommProp(parseDouble(request.getCommProp()));
			productSku.setHighestComm(parseDouble(request.getHighestComm()));
			productSkuMapper.insertSelective(productSku);
		}
		
		return product.getProductId();
	}

	@Override
	public void modifyProductInfo(ModifyProductInfoRequest request) throws Exception {
		logger.info("编辑商品信息");
		Product product = new Product();
		Long productId = request.getProductId();
		product.setProductId(productId);
		if(!StringUtils.isBlank(request.getProductName()))
			product.setName(request.getProductName());
		if(!StringUtils.isBlank(request.getProductDesc()))
			product.setProductDesc(request.getProductDesc());
		product.setModifierId(request.getOperId());
		product.setModifyTime(DateUtil.getSysDate());
		if(!StringUtils.isBlank(request.getGmProductId()) || !StringUtils.isBlank(request.getGmSkuid()))
			product.setParam(request.getGmProductId()+EmallBusiConstants.Product.PARAM_SPLIT+request.getGmSkuid());
		if(!StringUtils.isBlank(request.getProductLink()))
			product.setDrainageUrl(request.getProductLink());
		productMapper.updateByPrimaryKeySelective(product);
		
		//活动区和广告区不需要保存sku表
		if(!request.getModuleId().equals(EmallBusiConstants.MallProductModule.ModuleId.AREA_ACTIVITY) 
				&& !request.getModuleId().equals(EmallBusiConstants.MallProductModule.ModuleId.AREA_ADVERTISEMENT)){
			logger.info("编辑商品SKU表");
			//通过productId查询所有的productSku
			List<ProductSku> productSkus = iProductSkuSV.getBeansByProductId(productId);
			if(CollectionUtil.isEmpty(productSkus))
				throw new BusinessException(SysExceptCodeConstants.Special.NO_RESULT, "根据productId["+productId+"]没有在productsku中找到数据");
			ProductSku productSku = productSkus.get(0);
			productSku.setPriceMode(request.getPriceType());
			productSku.setNormalPrice(parseDouble(request.getNormalPrice()));
			productSku.setDiscount(parseDouble(request.getDisCount()));
			productSku.setSailPrice(parseDouble(request.getSailPrice()));
			productSku.setSailPriceTs(DateUtil.getCurrentTimeMillis());
			productSku.setCommProp(parseDouble(request.getCommProp()));
			productSku.setHighestComm(parseDouble(request.getHighestComm()));
			productSku.setModifierId(request.getOperId());
			productSku.setModifyTime(DateUtil.getSysDate());
			productSkuMapper.updateByPrimaryKeySelective(productSku);
		}
		
		if(!StringUtils.isBlank(request.getProductPictureDir())){
			logger.info("编辑商品图片");
			//通过productId查询模块信息
			List<MallProductModule> modules = iMallProductModuleSV.getBeansByProductId(productId);
			if(CollectionUtil.isEmpty(modules))
				throw new BusinessException(SysExceptCodeConstants.Special.NO_RESULT, "根据productId["+productId+"]在MallProductModule中没有找到相关数据");
			ProductPicture productPicture = new ProductPicture();
			Long picId = modules.get(0).getPictId();
			productPicture.setPicId(picId);
			productPicture.setVfsId(request.getProductPictureDir());
			pictureMapper.updateByPrimaryKeySelective(productPicture);
		}
		
	}

	@Override
	public void modifyProductStatus(List<Long> productIds,String status,Long operId) throws Exception {
		String skuStatus = "";
		String moduleStatus = null;
		if(status.equals(EmallBusiConstants.ProductSku.Status.DELETE)){
			skuStatus = EmallBusiConstants.ProductSku.Status.DELETE;
			moduleStatus = EmallBusiConstants.MallProductModule.Status.DELETE;
		}else if(status.equals(EmallBusiConstants.ProductSku.Status.DOWN)){
			skuStatus = EmallBusiConstants.ProductSku.Status.DOWN;
			moduleStatus = EmallBusiConstants.MallProductModule.Status.DOWN;
		}else if(status.equals(EmallBusiConstants.ProductSku.Status.UP)){
			skuStatus = EmallBusiConstants.ProductSku.Status.UP;
			moduleStatus = EmallBusiConstants.MallProductModule.Status.UP;
		}else
			throw new BusinessException(SysExceptCodeConstants.Special.PARAM_TYPE_NOT_RIGHT, "参数状态不正确：status必须是下架00，上架：01,删除：02其中之一");
		//查询商品模块表
		List<MallProductModule> mallProductModules = iMallProductModuleSV.getBeansByProductIds(productIds);
		if(!CollectionUtil.isEmpty(mallProductModules)){
			for (MallProductModule productModule : mallProductModules) {
				logger.info("修改商品模块ProductID["+productModule.getPmId()+"]状态，旧状态："+productModule.getStatus()+"->新状态："+moduleStatus);
				productModule.setStatus(moduleStatus);
				productModule.setModifierId(operId);
				productModule.setModifyTime(DateUtil.getSysDate());
				if(moduleStatus != EmallBusiConstants.MallProductModule.Status.DELETE){//不等于删除，需将该商品排到上架/下架的最前面
					Long maxsort = iMallProductModuleSV.getMaxSortByModuleId(productModule.getModuleId(), moduleStatus);
					productModule.setModuleSort(maxsort+1);
				}
				moduleMapper.updateByPrimaryKeySelective(productModule);
			}
		}
		//查询商品SKU表
		List<ProductSku> ProductSkus = iProductSkuSV.getBeansByProductIds(productIds);
		if(!CollectionUtil.isEmpty(ProductSkus)){
			for (ProductSku ProductSku : ProductSkus) {
				logger.info("修改商品sku表SKUID["+ProductSku.getSkuId()+"]状态，旧状态："+ProductSku.getStatus()+"->新状态："+skuStatus);
				ProductSku.setStatus(skuStatus);
				ProductSku.setModifierId(operId);
				ProductSku.setModifyTime(DateUtil.getSysDate());
				productSkuMapper.updateByPrimaryKeySelective(ProductSku);
			}
		}
				
	}

	@Override
	public void modifyProductSort(Long productId, Integer sortType, String moduleId, Long operId)
			throws Exception {
		//查询排好序的商品模块表
		MallProductModuleExample moduleExample = new MallProductModuleExample();
		Criteria sql = moduleExample.createCriteria();
		sql.andModuleIdEqualTo(moduleId);
		sql.andStatusEqualTo(EmallBusiConstants.MallProductModule.Status.UP);//目前仅针对上架商品允许上移/下移
		moduleExample.setOrderByClause("module_sort desc");
		List<MallProductModule> productModules = moduleMapper.selectByExample(moduleExample);
		if(!CollectionUtil.isEmpty(productModules)){
			MallProductModule oldSortBean = null;//交换的bean
			MallProductModule newSortBean = null;//交换的bean
			for (MallProductModule productModule : productModules) {
				if(productModule.getProductId() == productId){
					oldSortBean = productModule;
					if(sortType == EmallBusiConstants.MallProductModule.SortType.UP)
						break;
				}else{
					newSortBean = productModule;
					if(oldSortBean!=null && sortType == EmallBusiConstants.MallProductModule.SortType.DOWN)
						break;
				}
			}
			if(newSortBean==null || oldSortBean == null)
				return;
			
			//开始交换两个bean的sort
			Long sortNumTmp = oldSortBean.getModuleSort();
			oldSortBean.setModuleSort(newSortBean.getModuleSort());
			oldSortBean.setModifierId(operId);
			oldSortBean.setModifyTime(DateUtil.getSysDate());
			moduleMapper.updateByPrimaryKeySelective(oldSortBean);
			
			newSortBean.setModuleSort(sortNumTmp);
			newSortBean.setModifierId(operId);
			newSortBean.setModifyTime(DateUtil.getSysDate());
			moduleMapper.updateByPrimaryKeySelective(newSortBean);
		}
	}
	private double parseDouble(Double val){
		return (Double)ObjectUtils.defaultIfNull(val, 0.00);
	}
}

